package com.windaka.elements.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.windaka.elements.annotation.RepeatSubmit;
import com.windaka.elements.utils.ServletUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Method;

/**
 * @author wangning
 * @version 1.0
 * Create by 2024/2/23 15:44
 */
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {

    private static final String ERROR_JSON = "{\"msg\": \"\", \"code\": 500, \"data\": null}";

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception
    {
        if (handler instanceof HandlerMethod)
        {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null)
            {
                if (this.isRepeatSubmit(request, annotation))
                {
                    JSONObject jsonObject = JSON.parseObject(ERROR_JSON);
                    jsonObject.put("msg", annotation.message());
                    ServletUtils.renderString(response, jsonObject.toJSONString());
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request
     * @return
     * @throws Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
}
